import { colorUtils, timeUtils } from './index'

/**
 * ECharts 图表配置工具
 */

// 通用图表配置
export const commonChartOptions = {
  // 网格配置
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  
  // 工具箱配置
  toolbox: {
    feature: {
      saveAsImage: {
        title: '保存为图片'
      },
      dataZoom: {
        title: {
          zoom: '区域缩放',
          back: '区域缩放还原'
        }
      },
      restore: {
        title: '还原'
      }
    }
  },
  
  // 数据缩放配置
  dataZoom: [
    {
      type: 'inside',
      start: 0,
      end: 100
    },
    {
      start: 0,
      end: 100,
      height: 30
    }
  ],
  
  // 动画配置
  animation: true,
  animationDuration: 1000,
  animationEasing: 'cubicOut'
}

// 颜色主题
export const chartColors = {
  primary: ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#fa8c16'],
  temperature: '#f5222d',
  humidity: '#1890ff',
  pressure: '#52c41a',
  light: '#faad14',
  gradient: {
    temperature: {
      type: 'linear',
      x: 0, y: 0, x2: 0, y2: 1,
      colorStops: [
        { offset: 0, color: 'rgba(245, 34, 45, 0.8)' },
        { offset: 1, color: 'rgba(245, 34, 45, 0.1)' }
      ]
    },
    humidity: {
      type: 'linear',
      x: 0, y: 0, x2: 0, y2: 1,
      colorStops: [
        { offset: 0, color: 'rgba(24, 144, 255, 0.8)' },
        { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
      ]
    },
    pressure: {
      type: 'linear',
      x: 0, y: 0, x2: 0, y2: 1,
      colorStops: [
        { offset: 0, color: 'rgba(82, 196, 26, 0.8)' },
        { offset: 1, color: 'rgba(82, 196, 26, 0.1)' }
      ]
    },
    light: {
      type: 'linear',
      x: 0, y: 0, x2: 0, y2: 1,
      colorStops: [
        { offset: 0, color: 'rgba(250, 173, 20, 0.8)' },
        { offset: 1, color: 'rgba(250, 173, 20, 0.1)' }
      ]
    }
  }
}

/**
 * 创建折线图配置
 */
export const createLineChartOption = ({
  title = '',
  data = [],
  xAxisKey = 'time',
  yAxisKey = 'value',
  unit = '',
  color = chartColors.primary[0],
  smooth = true,
  area = false,
  showSymbol = false
}) => {
  const xData = data.map(item => timeUtils.format(item[xAxisKey], 'HH:mm'))
  const yData = data.map(item => item[yAxisKey])
  
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const param = params[0]
        const time = timeUtils.format(data[param.dataIndex][xAxisKey])
        return `${time}<br/>${param.seriesName}: ${param.value}${unit}`
      }
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: unit,
      axisLabel: {
        formatter: `{value}${unit}`
      }
    },
    series: [{
      name: title,
      type: 'line',
      data: yData,
      smooth,
      showSymbol,
      lineStyle: {
        color,
        width: 2
      },
      itemStyle: {
        color
      },
      areaStyle: area ? {
        color: typeof color === 'string' ? colorUtils.addAlpha(color, 0.3) : color
      } : null
    }],
    ...commonChartOptions
  }
}

/**
 * 创建多系列折线图配置
 */
export const createMultiLineChartOption = ({
  title = '',
  data = [],
  series = [],
  xAxisKey = 'time',
  unit = ''
}) => {
  const xData = data.map(item => timeUtils.format(item[xAxisKey], 'HH:mm'))
  
  const seriesData = series.map((serie, index) => ({
    name: serie.name,
    type: 'line',
    data: data.map(item => item[serie.key]),
    smooth: true,
    showSymbol: false,
    lineStyle: {
      color: serie.color || chartColors.primary[index % chartColors.primary.length],
      width: 2
    },
    itemStyle: {
      color: serie.color || chartColors.primary[index % chartColors.primary.length]
    }
  }))
  
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const time = timeUtils.format(data[params[0].dataIndex][xAxisKey])
        let content = `${time}<br/>`
        params.forEach(param => {
          content += `${param.seriesName}: ${param.value}${unit}<br/>`
        })
        return content
      }
    },
    legend: {
      data: series.map(s => s.name),
      top: 30
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: unit,
      axisLabel: {
        formatter: `{value}${unit}`
      }
    },
    series: seriesData,
    ...commonChartOptions
  }
}

/**
 * 创建柱状图配置
 */
export const createBarChartOption = ({
  title = '',
  data = [],
  xAxisKey = 'name',
  yAxisKey = 'value',
  unit = '',
  color = chartColors.primary[0]
}) => {
  const xData = data.map(item => item[xAxisKey])
  const yData = data.map(item => item[yAxisKey])
  
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const param = params[0]
        return `${param.name}<br/>${param.seriesName}: ${param.value}${unit}`
      }
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: unit,
      axisLabel: {
        formatter: `{value}${unit}`
      }
    },
    series: [{
      name: title,
      type: 'bar',
      data: yData,
      itemStyle: {
        color: typeof color === 'string' ? {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color },
            { offset: 1, color: colorUtils.addAlpha(color, 0.6) }
          ]
        } : color
      }
    }],
    ...commonChartOptions
  }
}

/**
 * 创建饼图配置
 */
export const createPieChartOption = ({
  title = '',
  data = [],
  nameKey = 'name',
  valueKey = 'value',
  unit = '',
  radius = ['40%', '70%']
}) => {
  const pieData = data.map((item, index) => ({
    name: item[nameKey],
    value: item[valueKey],
    itemStyle: {
      color: chartColors.primary[index % chartColors.primary.length]
    }
  }))
  
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}' + unit + ' ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item[nameKey])
    },
    series: [{
      name: title,
      type: 'pie',
      radius,
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '30',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: pieData
    }]
  }
}

/**
 * 创建仪表盘配置
 */
export const createGaugeChartOption = ({
  title = '',
  value = 0,
  min = 0,
  max = 100,
  unit = '',
  color = chartColors.primary[0],
  thresholds = []
}) => {
  // 根据阈值设置颜色
  let gaugeColor = color
  if (thresholds.length > 0) {
    for (const threshold of thresholds) {
      if (value >= threshold.min && value <= threshold.max) {
        gaugeColor = threshold.color
        break
      }
    }
  }
  
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    series: [{
      name: title,
      type: 'gauge',
      min,
      max,
      splitNumber: 10,
      radius: '80%',
      axisLine: {
        lineStyle: {
          width: 10,
          color: [
            [0.3, '#67e0e3'],
            [0.7, '#37a2da'],
            [1, '#fd666d']
          ]
        }
      },
      pointer: {
        itemStyle: {
          color: gaugeColor
        }
      },
      axisTick: {
        distance: -30,
        length: 8,
        lineStyle: {
          color: '#fff',
          width: 2
        }
      },
      splitLine: {
        distance: -30,
        length: 30,
        lineStyle: {
          color: '#fff',
          width: 4
        }
      },
      axisLabel: {
        color: 'auto',
        distance: 40,
        fontSize: 12,
        formatter: `{value}${unit}`
      },
      detail: {
        valueAnimation: true,
        formatter: `{value}${unit}`,
        color: 'auto',
        fontSize: 20,
        offsetCenter: [0, '70%']
      },
      data: [{
        value,
        name: title
      }]
    }]
  }
}

/**
 * 创建雷达图配置
 */
export const createRadarChartOption = ({
  title = '',
  data = [],
  indicators = [],
  max = 100
}) => {
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item'
    },
    radar: {
      indicator: indicators.map(indicator => ({
        name: indicator.name,
        max: indicator.max || max
      })),
      radius: '70%'
    },
    series: [{
      name: title,
      type: 'radar',
      data: data.map((item, index) => ({
        value: item.value,
        name: item.name,
        itemStyle: {
          color: chartColors.primary[index % chartColors.primary.length]
        },
        areaStyle: {
          color: colorUtils.addAlpha(chartColors.primary[index % chartColors.primary.length], 0.3)
        }
      }))
    }]
  }
}

/**
 * 创建散点图配置
 */
export const createScatterChartOption = ({
  title = '',
  data = [],
  xAxisKey = 'x',
  yAxisKey = 'y',
  xAxisName = '',
  yAxisName = '',
  color = chartColors.primary[0]
}) => {
  const scatterData = data.map(item => [item[xAxisKey], item[yAxisKey]])
  
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        return `${xAxisName}: ${params.value[0]}<br/>${yAxisName}: ${params.value[1]}`
      }
    },
    xAxis: {
      type: 'value',
      name: xAxisName,
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: yAxisName,
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: title,
      type: 'scatter',
      data: scatterData,
      symbolSize: 8,
      itemStyle: {
        color
      }
    }],
    ...commonChartOptions
  }
}

/**
 * 创建热力图配置
 */
export const createHeatmapChartOption = ({
  title = '',
  data = [],
  xAxisData = [],
  yAxisData = [],
  min = 0,
  max = 100
}) => {
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      position: 'top',
      formatter: (params) => {
        return `${yAxisData[params.value[1]]}<br/>${xAxisData[params.value[0]]}: ${params.value[2]}`
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      splitArea: {
        show: true
      }
    },
    yAxis: {
      type: 'category',
      data: yAxisData,
      splitArea: {
        show: true
      }
    },
    visualMap: {
      min,
      max,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '15%',
      inRange: {
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffcc', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      }
    },
    series: [{
      name: title,
      type: 'heatmap',
      data,
      label: {
        show: true
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
}

/**
 * 传感器数据图表配置
 */
export const sensorChartConfigs = {
  // 组合图表（温度、湿度、气压、光照强度）
  combined: (data) => {
    if (!data || data.length === 0) return { title: { text: '暂无数据' } }
    
    // 检查数据格式，判断是原始数据还是聚合数据
    const isAggregatedData = data[0] && (data[0].hour || data[0].date || data[0].month || 
                                         data[0].avgTemperature || data[0].avgHumidity);
    console.log('是否为聚合数据:', isAggregatedData);
    console.log('数据样本:', data[0]);
    
    // 根据数据量选择合适的时间格式
    let timeFormat = 'HH:mm'
    if (data.length > 48) {
      timeFormat = 'MM-DD HH:mm'
    }
    if (data.length > 300) {
      timeFormat = 'MM-DD'
    }
    if (data.length > 1000) {
      timeFormat = 'MM/DD'
    }
    
    // 确定X轴数据
    let xData;
    let timeField;
    if (isAggregatedData) {
      // 聚合数据的时间字段可能是hour, date, month
      timeField = data[0].hour ? 'hour' : (data[0].date ? 'date' : (data[0].month ? 'month' : 'time'));
      console.log('时间字段:', timeField);
      
      if (timeField === 'month') {
        // 月度数据的格式化
        xData = data.map(item => {
          const dateStr = item[timeField];
          return dateStr ? (typeof dateStr === 'string' ? dateStr.substring(0, 7) : dateStr) : '未知';
        });
      } else {
        // 小时或日数据的格式化
        xData = data.map(item => {
          const dateStr = item[timeField];
          return dateStr || '未知';
        });
      }
    } else {
      // 原始数据使用createdAt
      xData = data.map(item => timeUtils.format(item.createdAt || item.time, timeFormat));
    }
    
    // 根据数据量计算适当的标签间隔
    const labelInterval = calculateLabelInterval(data.length);
    console.log('标签间隔:', labelInterval);
    
    // 优化大数据量的显示配置
    const dataZoomConfig = [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        start: data.length > 48 ? 70 : 0,
        end: 100,
        height: 30,
        bottom: 10,
        borderColor: '#ccc',
        fillerColor: 'rgba(144,197,237,0.2)',
        handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4v-86.2c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
        handleSize: '110%',
        handleStyle: {
          color: '#d3dee5'
        },
        textStyle: {
          color: '#999'
        },
        emphasis: {
          handleStyle: {
            color: '#8fb0d7'
          }
        }
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        start: data.length > 48 ? 70 : 0,
        end: 100,
        zoomOnMouseWheel: true,
        moveOnMouseMove: true
      }
    ];
    
    // 确定数据字段名
    const temperatureField = isAggregatedData ? 'avgTemperature' : 'temperature';
    const humidityField = isAggregatedData ? 'avgHumidity' : 'humidity';
    const pressureField = isAggregatedData ? 'avgPressure' : 'pressure';
    const lightField = isAggregatedData ? 'avgLightIntensity' : 'lightIntensity';
    
    console.log('使用字段:', {
      temperatureField,
      humidityField,
      pressureField,
      lightField
    });
    
    return {
      title: {
        text: '传感器数据综合图表',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          // 使用索引获取时间
          const timeInfo = isAggregatedData ? 
            (data[params[0].dataIndex][timeField] || '未知时间') : 
            timeUtils.format(data[params[0].dataIndex].createdAt || data[params[0].dataIndex].time);
            
          let content = `${timeInfo}<br/>`
          
          params.forEach(param => {
            let value = param.value;
            if (value === null || value === undefined) return;
            
            let unit = ''
            
            if (param.seriesName === '温度') unit = '°C'
            else if (param.seriesName === '湿度') unit = '%'
            else if (param.seriesName === '气压') unit = 'hPa'
            else if (param.seriesName === '光照强度') unit = 'lux'
            
            if (param.seriesName === '气压') value = (value).toFixed(0)
            else if (param.seriesName === '温度' || param.seriesName === '湿度') value = value.toFixed(1)
            
            content += `${param.marker} ${param.seriesName}: ${value}${unit}<br/>`
          })
          return content
        }
      },
      legend: {
        data: ['温度', '湿度', '气压', '光照强度'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%', // 增加底部空间以适应数据缩放组件
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLabel: {
          rotate: 45,
          interval: labelInterval,
          formatter: function(value) {
            // 根据数据量截断标签
            if (data.length > 300) {
              return value.length > 10 ? value.substring(0, 10) + '...' : value;
            }
            return value;
          },
          margin: 14,
          align: 'center',
          fontSize: 11
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '温度(°C)/湿度(%)',
          min: 0,
          max: 100,
          position: 'left',
          splitLine: {
            show: true
          }
        },
        {
          type: 'value',
          name: '气压(hPa)',
          min: 900,
          max: 1100,
          position: 'right',
          offset: 0,
          splitLine: {
            show: false
          }
        },
        {
          type: 'value',
          name: '光照强度(lux)',
          min: 0,
          max: 2000,
          position: 'right',
          offset: 80,
          splitLine: {
            show: false
          }
        }
      ],
      series: [
        {
          name: '温度',
          type: 'line',
          data: data.map(item => {
            const value = item[temperatureField];
            return value !== undefined ? Number(value) : null;
          }),
          smooth: true,
          showSymbol: data.length < 48,
          lineStyle: { color: chartColors.temperature, width: 2 },
          itemStyle: { color: chartColors.temperature }
        },
        {
          name: '湿度',
          type: 'line',
          data: data.map(item => {
            const value = item[humidityField];
            return value !== undefined ? Number(value) : null;
          }),
          smooth: true,
          showSymbol: data.length < 48,
          lineStyle: { color: chartColors.humidity, width: 2 },
          itemStyle: { color: chartColors.humidity }
        },
        {
          name: '气压',
          type: 'line',
          yAxisIndex: 1,
          data: data.map(item => {
            const value = item[pressureField];
            return value !== undefined ? Number(value) / 100 : null;
          }),
          smooth: true,
          showSymbol: data.length < 48,
          lineStyle: { color: chartColors.pressure, width: 2 },
          itemStyle: { color: chartColors.pressure }
        },
        {
          name: '光照强度',
          type: 'line',
          yAxisIndex: 2,
          data: data.map(item => {
            const value = item[lightField];
            return value !== undefined ? Number(value) : null;
          }),
          smooth: true,
          showSymbol: data.length < 48,
          lineStyle: { color: chartColors.light, width: 2 },
          itemStyle: { color: chartColors.light }
        }
      ],
      dataZoom: dataZoomConfig,
      toolbox: {
        feature: {
          saveAsImage: { title: '保存图片' },
          dataZoom: { title: { zoom: '区域缩放', back: '区域缩放还原' } },
          restore: { title: '还原' },
          dataView: { title: '数据视图', lang: ['数据视图', '关闭', '刷新'] }
        }
      }
    }
  },
  
  // 多系列折线图
  multiSeries: (data, series = ['temperature', 'humidity', 'pressure', 'lightIntensity']) => {
    if (!data || data.length === 0) return { title: { text: '暂无数据' } }
    
    // 检查数据格式，判断是原始数据还是聚合数据
    const isAggregatedData = data[0] && (data[0].hour || data[0].date || data[0].month || 
                                         data[0].avgTemperature || data[0].avgHumidity);
    console.log('是否为聚合数据:', isAggregatedData);
    console.log('数据样本:', data[0]);
    
    // 根据数据量选择合适的时间格式
    let timeFormat = 'HH:mm'
    if (data.length > 48) {
      timeFormat = 'MM-DD HH:mm'
    }
    if (data.length > 300) {  // 对于长时间范围数据，只显示日期
      timeFormat = 'MM-DD'
    }
    if (data.length > 1000) {  // 对于超长时间范围数据，使用更简洁的月份格式
      timeFormat = 'MM/DD'
    }
    
    // 确定X轴数据
    let xData;
    let timeField;
    if (isAggregatedData) {
      // 聚合数据的时间字段可能是hour, date, month
      timeField = data[0].hour ? 'hour' : (data[0].date ? 'date' : (data[0].month ? 'month' : 'time'));
      console.log('时间字段:', timeField);
      
      if (timeField === 'month') {
        // 月度数据的格式化
        xData = data.map(item => {
          const dateStr = item[timeField];
          return dateStr ? (typeof dateStr === 'string' ? dateStr.substring(0, 7) : dateStr) : '未知';
        });
      } else {
        // 小时或日数据的格式化
        xData = data.map(item => {
          const dateStr = item[timeField];
          return dateStr || '未知';
        });
      }
    } else {
      // 原始数据使用createdAt
      xData = data.map(item => timeUtils.format(item.createdAt || item.time, timeFormat));
    }
    
    // 根据数据量计算适当的标签间隔
    const labelInterval = calculateLabelInterval(data.length);
    
    const seriesConfig = []
    
    const seriesMap = {
      temperature: {
        name: '温度',
        unit: '°C',
        color: chartColors.temperature,
        formatter: value => value.toFixed(1)
      },
      humidity: {
        name: '湿度',
        unit: '%',
        color: chartColors.humidity,
        formatter: value => value.toFixed(1)
      },
      pressure: {
        name: '气压',
        unit: 'hPa',
        color: chartColors.pressure,
        formatter: value => (value / 100).toFixed(0)
      },
      lightIntensity: {
        name: '光照强度',
        unit: 'lux',
        color: chartColors.light,
        formatter: value => value
      }
    }
    
    // 添加选中的系列
    series.forEach(key => {
      if (seriesMap[key]) {
        const config = seriesMap[key]
        
        // 确定数据字段名
        let dataKey = key;
        if (isAggregatedData) {
          // 聚合数据的字段可能是avgTemp, avgTemperature等
          if (key === 'temperature') {
            dataKey = data[0].avgTemperature !== undefined ? 'avgTemperature' : 'avgTemp';
          } else if (key === 'humidity') {
            dataKey = data[0].avgHumidity !== undefined ? 'avgHumidity' : 'avgHum';
          } else if (key === 'pressure') {
            dataKey = data[0].avgPressure !== undefined ? 'avgPressure' : 'avgPress';
          } else if (key === 'lightIntensity') {
            dataKey = data[0].avgLightIntensity !== undefined ? 'avgLightIntensity' : 'avgLight';
          }
        }
        
        console.log(`系列 ${key} 使用数据字段: ${dataKey}`);
        
        seriesConfig.push({
          name: config.name,
          type: 'line',
          data: data.map(item => {
            // 处理不同格式的数据
            let value;
            if (typeof item === 'object') {
              value = item[dataKey];
            }
            
            if (value === undefined || value === null) {
              console.warn(`数据项缺少字段 ${dataKey}:`, item);
              return null;
            }
            
            // 确保值是数字
            value = Number(value);
            
            return key === 'pressure' || dataKey === 'avgPressure' || dataKey === 'avgPress' ? 
                   value / 100 : value;
          }),
          smooth: true,
          showSymbol: data.length < 48, // 数据点过多时不显示标记点
          lineStyle: { color: config.color, width: 2 },
          itemStyle: { color: config.color }
        })
      }
    })
    
    // 优化大数据量的显示
    let dataZoomConfig = [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        start: data.length > 48 ? 70 : 0,
        end: 100,
        height: 30,
        bottom: 10,
        borderColor: '#ccc',
        fillerColor: 'rgba(144,197,237,0.2)',
        handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4v-86.2c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
        handleSize: '110%',
        handleStyle: {
          color: '#d3dee5'
        },
        textStyle: {
          color: '#999'
        },
        emphasis: {
          handleStyle: {
            color: '#8fb0d7'
          }
        }
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        start: data.length > 48 ? 70 : 0,
        end: 100,
        zoomOnMouseWheel: true,
        moveOnMouseMove: true
      }
    ];
    
    // 为大数据量优化工具箱配置
    const toolboxConfig = {
      feature: {
        saveAsImage: { title: '保存图片' },
        dataZoom: { title: { zoom: '区域缩放', back: '区域缩放还原' } },
        restore: { title: '还原' },
        dataView: { title: '数据视图', lang: ['数据视图', '关闭', '刷新'] }
      }
    }
    
    return {
      title: {
        text: '传感器数据趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          const timeInfo = isAggregatedData ? 
            (data[params[0].dataIndex][timeField] || '未知时间') : 
            timeUtils.format(data[params[0].dataIndex].createdAt || data[params[0].dataIndex].time);
          let content = `${timeInfo}<br/>`
          params.forEach(param => {
            if (param.value === null || param.value === undefined) return;
            
            const seriesKey = series[param.seriesIndex]
            const config = seriesMap[seriesKey]
            if (config) {
              const value = config.formatter(param.value)
              content += `${param.marker} ${param.seriesName}: ${value}${config.unit}<br/>`
            }
          })
          return content
        }
      },
      legend: {
        data: seriesConfig.map(s => s.name),
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%', // 增加底部空间以适应数据缩放组件
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLabel: {
          rotate: 45,
          interval: labelInterval,
          formatter: function(value) {
            // 根据数据量截断标签
            if (data.length > 300) {
              return value.length > 10 ? value.substring(0, 10) + '...' : value;
            }
            return value;
          },
          margin: 14,
          align: 'center',
          fontSize: 11
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          show: true
        }
      },
      series: seriesConfig,
      dataZoom: dataZoomConfig,
      toolbox: toolboxConfig
    }
  },
  
  // 柱状图
  bar: (data, series = ['temperature', 'humidity', 'pressure', 'lightIntensity']) => {
    if (!data || data.length === 0) return { title: { text: '暂无数据' } }
    
    // 检查数据格式，判断是原始数据还是聚合数据
    const isAggregatedData = data[0] && (data[0].hour || data[0].date || data[0].month || 
                                         data[0].avgTemperature || data[0].avgHumidity);
    console.log('是否为聚合数据:', isAggregatedData);
    console.log('数据样本:', data[0]);
    
    // 根据数据量选择合适的时间格式
    let timeFormat = 'HH:mm'
    if (data.length > 48) {
      timeFormat = 'MM-DD HH:mm'
    }
    if (data.length > 300) {
      timeFormat = 'MM-DD'
    }
    if (data.length > 1000) {
      timeFormat = 'MM/DD'
    }
    
    // 确定X轴数据
    let xData;
    let timeField;
    if (isAggregatedData) {
      // 聚合数据的时间字段可能是hour, date, month
      timeField = data[0].hour ? 'hour' : (data[0].date ? 'date' : (data[0].month ? 'month' : 'time'));
      console.log('时间字段:', timeField);
      
      if (timeField === 'month') {
        // 月度数据的格式化
        xData = data.map(item => {
          const dateStr = item[timeField];
          return dateStr ? (typeof dateStr === 'string' ? dateStr.substring(0, 7) : dateStr) : '未知';
        });
      } else {
        // 小时或日数据的格式化
        xData = data.map(item => {
          const dateStr = item[timeField];
          return dateStr || '未知';
        });
      }
    } else {
      // 原始数据使用createdAt
      xData = data.map(item => timeUtils.format(item.createdAt || item.time, timeFormat));
    }
    
    // 根据数据量计算适当的标签间隔
    const labelInterval = calculateLabelInterval(data.length);
    
    const seriesConfig = []
    
    const seriesMap = {
      temperature: {
        name: '温度',
        color: chartColors.temperature,
        formatter: value => value
      },
      humidity: {
        name: '湿度',
        color: chartColors.humidity,
        formatter: value => value
      },
      pressure: {
        name: '气压',
        color: chartColors.pressure,
        formatter: value => value / 100
      },
      lightIntensity: {
        name: '光照强度',
        color: chartColors.light,
        formatter: value => value / 10 // 缩放以便显示
      }
    }
    
    // 添加选中的系列
    series.forEach(key => {
      if (seriesMap[key]) {
        const config = seriesMap[key]
        
        // 确定数据字段名
        let dataKey = key;
        if (isAggregatedData) {
          // 聚合数据的字段可能是avgTemp, avgTemperature等
          if (key === 'temperature') {
            dataKey = data[0].avgTemperature !== undefined ? 'avgTemperature' : 'avgTemp';
          } else if (key === 'humidity') {
            dataKey = data[0].avgHumidity !== undefined ? 'avgHumidity' : 'avgHum';
          } else if (key === 'pressure') {
            dataKey = data[0].avgPressure !== undefined ? 'avgPressure' : 'avgPress';
          } else if (key === 'lightIntensity') {
            dataKey = data[0].avgLightIntensity !== undefined ? 'avgLightIntensity' : 'avgLight';
          }
        }
        
        seriesConfig.push({
          name: config.name,
          type: 'bar',
          data: data.map(item => {
            // 处理不同格式的数据
            let value;
            if (typeof item === 'object') {
              value = item[dataKey];
            }
            
            if (value === undefined || value === null) {
              return null;
            }
            
            // 确保值是数字
            value = Number(value);
            
            return config.formatter ? config.formatter(value) : value;
          }),
          itemStyle: { color: config.color },
          // 大数据量时使用更窄的柱宽
          barWidth: data.length > 100 ? '60%' : '80%'
        })
      }
    })
    
    // 优化大数据量的缩放配置
    const dataZoomConfig = [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        start: data.length > 48 ? 70 : 0,
        end: 100,
        height: 30,
        bottom: 10,
        borderColor: '#ccc',
        fillerColor: 'rgba(144,197,237,0.2)',
        handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4v-86.2c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
        handleSize: '110%',
        handleStyle: {
          color: '#d3dee5'
        },
        textStyle: {
          color: '#999'
        },
        emphasis: {
          handleStyle: {
            color: '#8fb0d7'
          }
        }
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        start: data.length > 48 ? 70 : 0,
        end: 100,
        zoomOnMouseWheel: true,
        moveOnMouseMove: true
      }
    ];
    
    return {
      title: {
        text: '传感器数据柱状图',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          const timeInfo = isAggregatedData ? 
            (data[params[0].dataIndex][timeField] || '未知时间') : 
            timeUtils.format(data[params[0].dataIndex].createdAt || data[params[0].dataIndex].time);
          let content = `${timeInfo}<br/>`
          
          params.forEach(param => {
            if (param.value === null || param.value === undefined) return;
            
            let unit = ''
            if (param.seriesName === '温度') unit = '°C'
            else if (param.seriesName === '湿度') unit = '%'
            else if (param.seriesName === '气压') unit = 'hPa'
            else if (param.seriesName === '光照强度') unit = 'lux'
            
            content += `${param.marker} ${param.seriesName}: ${param.value}${unit}<br/>`
          })
          return content
        }
      },
      legend: {
        data: seriesConfig.map(s => s.name),
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLabel: {
          rotate: 45,
          interval: labelInterval,
          formatter: function(value) {
            // 根据数据量截断标签
            if (data.length > 300) {
              return value.length > 10 ? value.substring(0, 10) + '...' : value;
            }
            return value;
          },
          margin: 14,
          align: 'center',
          fontSize: 11
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          show: true
        }
      },
      series: seriesConfig,
      dataZoom: dataZoomConfig,
      toolbox: {
        feature: {
          saveAsImage: { title: '保存图片' },
          dataZoom: { title: { zoom: '区域缩放', back: '区域缩放还原' } },
          restore: { title: '还原' },
          dataView: { title: '数据视图', lang: ['数据视图', '关闭', '刷新'] }
        }
      }
    }
  },
  
  // 散点图
  scatter: (data) => {
    if (!data || data.length === 0) return { title: { text: '暂无数据' } }
    
    return {
      title: {
        text: '温湿度关系散点图',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          const item = data[params.dataIndex]
          return `
            时间: ${timeUtils.format(item.createdAt)}<br/>
            温度: ${item.temperature.toFixed(1)}°C<br/>
            湿度: ${item.humidity.toFixed(1)}%<br/>
            气压: ${(item.pressure / 100).toFixed(0)}hPa<br/>
            光照: ${item.lightIntensity}lux
          `
        }
      },
      xAxis: {
        type: 'value',
        name: '温度(°C)',
        nameLocation: 'middle',
        nameGap: 30
      },
      yAxis: {
        type: 'value',
        name: '湿度(%)',
        nameLocation: 'middle',
        nameGap: 30
      },
      series: [
        {
          name: '温湿度关系',
          type: 'scatter',
          data: data.map(item => [item.temperature, item.humidity]),
          symbolSize: (value) => {
            // 根据气压值调整散点大小
            const pressure = data.find(item => 
              item.temperature === value[0] && item.humidity === value[1]
            ).pressure
            return (pressure / 100000) * 20 + 5
          },
          itemStyle: {
            color: (params) => {
              // 根据光照强度设置颜色
              const light = data[params.dataIndex].lightIntensity
              return colorUtils.getLightColor(light)
            }
          }
        }
      ]
    }
  },
  
  // 热力图
  heatmap: (data) => {
    if (!data || data.length === 0) return { title: { text: '暂无数据' } }
    
    // 按小时分组数据
    const hours = [...new Set(data.map(item => 
      new Date(item.createdAt).getHours()
    ))].sort((a, b) => a - b)
    
    // 按日期分组数据
    const dates = [...new Set(data.map(item => 
      timeUtils.format(item.createdAt, 'MM-DD')
    ))].sort()
    
    // 生成热力图数据
    const heatmapData = []
    const temperatureData = []
    const humidityData = []
    
    dates.forEach((date, dateIndex) => {
      hours.forEach((hour, hourIndex) => {
        // 找出该日期和小时的所有数据
        const hourData = data.filter(item => 
          timeUtils.format(item.createdAt, 'MM-DD') === date &&
          new Date(item.createdAt).getHours() === hour
        )
        
        if (hourData.length > 0) {
          // 计算平均值
          const avgTemp = hourData.reduce((sum, item) => sum + item.temperature, 0) / hourData.length
          const avgHumidity = hourData.reduce((sum, item) => sum + item.humidity, 0) / hourData.length
          
          temperatureData.push([hourIndex, dateIndex, avgTemp.toFixed(1)])
          humidityData.push([hourIndex, dateIndex, avgHumidity.toFixed(1)])
        }
      })
    })
    
    return {
      title: {
        text: '温湿度热力图',
        left: 'center'
      },
      tooltip: {
        position: 'top',
        formatter: (params) => {
          const date = dates[params.data[1]]
          const hour = hours[params.data[0]]
          const value = params.data[2]
          return `${date} ${hour}:00<br/>${params.seriesName}: ${value}${params.seriesName === '温度' ? '°C' : '%'}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: hours.map(h => `${h}:00`),
        splitArea: {
          show: true
        }
      },
      yAxis: {
        type: 'category',
        data: dates,
        splitArea: {
          show: true
        }
      },
      visualMap: {
        min: 0,
        max: 40,
        calculable: true,
        orient: 'horizontal',
        left: 'center',
        bottom: '0%',
        inRange: {
          color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
        }
      },
      series: [
        {
          name: '温度',
          type: 'heatmap',
          data: temperatureData,
          emphasis: {
            itemStyle: {
              borderColor: '#333',
              borderWidth: 1
            }
          },
          progressive: 1000,
          animation: false
        }
      ]
    }
  }
}

/**
 * 响应式图表配置
 */
export const getResponsiveChartOption = (baseOption, containerWidth) => {
  const option = { ...baseOption }
  
  if (containerWidth < 768) {
    // 移动端适配
    option.grid = {
      left: '5%',
      right: '5%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    }
    
    if (option.title) {
      option.title.textStyle = {
        ...option.title.textStyle,
        fontSize: 14
      }
    }
    
    if (option.xAxis && option.xAxis.axisLabel) {
      option.xAxis.axisLabel.fontSize = 10
      option.xAxis.axisLabel.rotate = 45
    }
    
    if (option.yAxis && option.yAxis.axisLabel) {
      option.yAxis.axisLabel.fontSize = 10
    }
    
    if (option.legend) {
      option.legend.textStyle = {
        fontSize: 10
      }
    }
  }
  
  return option
}

// 添加一个辅助函数来计算标签间隔
const calculateLabelInterval = (dataLength) => {
  if (dataLength <= 12) return 0; // 数据量小，全部显示
  if (dataLength <= 24) return 1; // 显示一半
  if (dataLength <= 48) return 3; // 显示1/4
  if (dataLength <= 100) return 5;
  if (dataLength <= 200) return 9;
  if (dataLength <= 500) return 19;
  return Math.floor(dataLength / 20); // 最多显示约20个标签
}

export default {
  commonChartOptions,
  chartColors,
  createLineChartOption,
  createMultiLineChartOption,
  createBarChartOption,
  createPieChartOption,
  createGaugeChartOption,
  createRadarChartOption,
  createScatterChartOption,
  createHeatmapChartOption,
  sensorChartConfigs,
  getResponsiveChartOption
}